// pages/home/home.js
// pages/class/class.js
var base = require('../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数
const PAGES = require('../../utils/pages.js')
const { HTTP } = require('../../lib/http.js')
const { URL } = require('../../lib/urls.js')
const { getUserToken, getUserInfo } = require('../../lib/user.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: [],
    showModal: false,
    selectData: null,
    classfiySelect: "",
    leftText: [],
    rightData: [],
    // totle:0.00,
    isStopBodyScroll:false,
    scrollTop:0,
    gun:true,
    conH:0,
    bannerInfos:[],
    headH:0,
    isCanAdd:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      _t: base._t(), //翻译
    });
    if (!getIsLogin()) {
      wx.navigateTo({
        url: PAGES.index,
      })
      return;
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.setData({
      conH: (wx.getSystemInfoSync().windowHeight < 605 ? 605 : wx.getSystemInfoSync().windowHeight) * 2-70
    })
    this.getNetTypeList();
    this.getNetGoodsList();
    this.getNetBannerList();//获取首页banner图
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    this.getCartCount();//获取购物车商品数量
    if (getApp().globalData.isShuaxinHome){
      //需要刷新首页
      this.getNetGoodsList();
      getApp().globalData.isShuaxinHome = false;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.getNetTypeList();
    this.getNetGoodsList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  //滚动触发
  scroll: function(e) {
    var scrollTop = e.detail.scrollTop,
      h = 0,
      classfiySelect;
    var that = this;
    that.data.leftText.forEach(function(clssfiy, i) {
      var _h = 35 + that.length(clssfiy['ProductTypeCode']) * 73;
      if (scrollTop >= h) {
        classfiySelect = clssfiy['ProductTypeCode'];
      }
      h += _h;
      console.log(h);
    })
    that.setData({
      classfiySelect: classfiySelect,
    })
  },
  //求每一栏高度
  length: function(e) {
    var that = this;
    var rightData = that.data.rightData;
    for (var i = 0; i < rightData.length; i++) {
      if (rightData[i]['ProductTypeCode'] == e) {
        return rightData[i]['ProductInfos'].length;

      }
    }
  },
  //点击左边事件
  left_list: function(e) {
    var that = this;
    var l_id = e.currentTarget.dataset.id;
    if (that.data.scrollTop < that.data.headH){
      wx.pageScrollTo({
        scrollTop: that.data.headH,
      })
      setTimeout(function () {
        that.setData({
          rigId: l_id,
          classfiySelect: l_id,
        })
      }, 1000) //延迟时间 这里是1秒
    }else{
      that.setData({
        rigId: l_id,
        classfiySelect: l_id,
      })
    }
    
  },
  //商品列表数量改变
  numchangeTap: function(e) {
    if(!this.data.isCanAdd){
      return;
    }
    var changType = e.currentTarget.dataset.types;
    var index = e.currentTarget.dataset.index;
    var section = e.currentTarget.dataset.section;
    var typeInfo=this.data.rightData[section];
    var istc = e.currentTarget.dataset.istc;
    if(changType=="add"){
      //数字增加
      if(istc){
        //弹窗内数字增加
        var model=this.data.selectData;
        model.amount+=1;
        this.setData({
          selectData:model,
          isCanAdd:false,
        })
        return;
      }
      this.setDataList(1, index, section, typeInfo);
    } else if (changType == "minus"){
      //减
      if (istc) {
        //弹窗内数字减少
        var model = this.data.selectData;
        if(model.amount<1){
          return;
        }
        model.amount -= 1;
        this.setData({
          selectData: model,
        })
        return;
      }
      var goodsModel=typeInfo.ProductInfos[index];
      if(goodsModel.amount<1){
        return;
      }
      this.setDataList(0, index, section, typeInfo);
    }
  },
  // 设置商品列表工具类
  setDataList: function (type, index, section, typeInfo) {
    // type:1加，0减
    // var pice = 0;//商品价格
    var list = [];//修改后列表
    for (var indexG in typeInfo.ProductInfos) {
      var goodsModel = typeInfo.ProductInfos[indexG];
      if (index == indexG) {
        goodsModel.amount = (type == 1 ? goodsModel.amount + 1 : goodsModel.amount-=1);
        goodsModel.isSelect = (goodsModel.amount>0?true:false);
        // pice = (type == 1 ? this.data.totle + goodsModel.SoldPrice : this.data.totle - goodsModel.SoldPrice);
        this.addCartTap(goodsModel);
      }
      list.push(goodsModel);
    }
    typeInfo.ProductInfos = list;
    // 开始设置商品列表
    var typeList = [];
    for (var i in this.data.rightData) {
      var typeModel = this.data.rightData[i];
      if (i == section) {
        typeModel = typeInfo;
      }
      typeList.push(typeModel);
    }
    this.setData({
      rightData: typeList,
      // totle: pice
    });
  },
  //跳转到商品详情页
  gotoGoodsInfoTap: function (e) {
    var item = e.currentTarget.dataset.item;
    var data = JSON.stringify(item);
    wx.navigateTo({
      url: PAGES.goodsInfo+'?data=' + data,
    });
  },

  //获取商品分类列表
  getNetTypeList: function () {
    let that = this;
    HTTP({
      url: URL.goods.productTypeList,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        var res = ress.Data;
        console.log("hlw:" + res)
        if (res.length > 0) {
          that.setData({
            leftText: res,
            classfiySelect: res[0].ProductTypeCode,
          });
        }
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //获取商品分类列表
  getNetGoodsList: function () {
    let that = this;
    HTTP({
      url: URL.goods.productList,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        var res = ress.Data;
        console.log("hlw:" + res)
        if (res.Infos.length > 0) {
          let list = [];
          // var hight=150;
          for (var index in res.Infos) {
            var model = res.Infos[index];
            // hight+=70;
            if (model.IsMerge == 1) {
              // hight +=122;
              //联合产品
              let productInfos = [];
              for (var i = 0; i < model.ProductInfos.length; i++) {
                var pro = model.ProductInfos[i];
                for (var cpindex in pro.CProductList) {
                  var cppro = pro.CProductList[cpindex];
                  productInfos.push(cppro);
                }
                if (i == 0) {
                  model.ProductCode = pro.ProductCode;
                  model.Price = pro.Price;
                  model.SoldPrice = pro.SoldPrice;
                  model.Status = pro.Status;
                  model.Count = pro.Count;
                  model.amount = 1;//默认0个
                }
              }
              model.ProductInfos = productInfos;
              // hight += 112 * model.ProductInfos.length+20;
            } else {
              // 普通商品数量设置
              let goodsInfos = [];
              for (var i = 0; i < model.ProductInfos.length; i++) {
                var pro = model.ProductInfos[i];
                pro.amount = 0;
                goodsInfos.push(pro);
              }
              model.ProductInfos = goodsInfos;
              // hight += 148 * model.ProductInfos.length;
            }
            list.push(model);
          }
          that.setData({
            rightData: list,
          });
        }
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //获取首页轮播图
  getNetBannerList: function () {
    var that = this;
    HTTP({
      url: URL.home.sysBannerList,
      userToken: getUserToken(),
      data: {
        MemberId: getUserInfo().memberId,
        BannerType:1,
      },
      success: (ress) => {
        var res = ress.Data;
        if (res.SysBannerInfos.length > 0) {
          that.setData({
            bannerInfos: res.SysBannerInfos,
          })
        }
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  showDialogBtn: function (e) {
    let Index = e.currentTarget.dataset.index;//点击的商品下标值
    let nowSelect = this.data.rightData[Index];
    var that = this
    that.setData({
      selectData: nowSelect,
      showModal: true,
    })
  },
  //获取购物车商品数量
  getCartCount: function () {
    let that = this;
    HTTP({
      url: URL.goods.cartCount,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        var res = ress.Data;
        console.log("hlw:" + res)
        var list=[];
        for (var i in that.getTabBar().data.list){
          var model = that.getTabBar().data.list[i];
          if(i==2){
            model.tagNum = res;
          }
          list.push(model);
        }
        that.getTabBar().setData({
          list:list
        })
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //添加到购物车
  addCartTap: function (goodsModel) {
    wx.showLoading({
      title: ''
    })
    var that = this;
    HTTP({
      url: URL.goods.changeCart,
      userToken: getUserToken(),
      data: {
        ProductCode: goodsModel.ProductCode,
        Count: 1,
        MemberId: getUserInfo().memberId,
        IsAdd:true,
      },
      success: (res) => {
        wx.hideLoading();
        wx.showToast({
          title: _('添加成功'),
        })
        that.getCartCount();
        that.setData({
          isCanAdd: true
        });
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        that.setData({
          isCanAdd: true
        });
      }
    })
  },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    var that = this
    that.setData({
      showModal: false
    });
  },
  // 提交订单
  submitTcTap: function () {
    let data = JSON.stringify(this.data.selectData);
    wx.navigateTo({
      url: PAGES.orderQrLh + '?data=' + encodeURIComponent(data)
    })
  },
  // 提交普通商品列表
  submitListTap: function () {
    //获取提交商品列表
    var list=[];
    for(var tindex in this.data.rightData){
      var tmodel=this.data.rightData[tindex];
      for(var gindex in tmodel.ProductInfos){
        var gmodel=tmodel.ProductInfos[gindex];
        if (gmodel.isSelect){
          list.push(gmodel);
        }
      }
    }
    let data = JSON.stringify(list);
    wx.navigateTo({
      url: PAGES.orderQrPt + '?data=' + encodeURIComponent(data),
    })
  },

  //监听屏幕滚动 判断上下滚动
  onPageScroll: function (ev) {
    var _this = this;
    console.log("ev.scrollTop:" + ev.scrollTop);
    //当滚动的top值最大或最小时，为什么要做这一步是因为在手机实测小程序的时候会发生滚动条回弹，所以为了处理回弹，设置默认最大最小值
    if (ev.scrollTop <= 0) {
      ev.scrollTop = 0;
    } else if (ev.scrollTop > wx.getSystemInfoSync().windowHeight) {
      ev.scrollTop = wx.getSystemInfoSync().windowHeight;
    }
    //判断浏览器滚动条上下滚动
    if (ev.scrollTop > this.data.scrollTop || ev.scrollTop == wx.getSystemInfoSync().windowHeight) {
      //向下滚动
      
    } else {
      //向上滚动
      
    }
    //给scrollTop重新赋值
    setTimeout(function () {
      _this.setData({
        scrollTop: ev.scrollTop,
        isStopBodyScroll: ev.scrollTop < that.data.headH ? true : false,
        gun: ev.scrollTop < that.data.headH ? false : true,
      })
      console.log("isStopBodyScroll:" + _this.data.isStopBodyScroll);
    }, 0)
  }
})